package com.satan.fmmall.controller;

import com.github.wxpay.sdk.WXPayUtil;
import com.satan.fmmall.service.OrderService;
import com.satan.fmmall.vo.ResCode;
import com.satan.fmmall.vo.ResultVo;
import com.satan.fmmall.websocket.WebSocketServer;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * @ClassName PayController
 * @Description TODO
 * @date 2022/4/18 12:43
 * @Version 1.0
 */
@RestController
@Api(tags = "支付回调接口",value = "用于处理支付成功后的操作")
@RequestMapping("/pay")
public class PayController {
    @Resource
    private OrderService orderService;
    @Resource
    private WebSocketServer webSocketServer;

    /**
     * 微信支付回调接口
     */
    @ApiOperation("微信支付回调接口")
    @GetMapping("/callback")
    public String success(HttpServletRequest request) throws Exception {
        System.out.println("---------------callback-----------");
        ServletInputStream inputStream = request.getInputStream();
        byte[] bytes = new byte[1024];
        int len = 0;
        StringBuilder sb = new StringBuilder();
        while ((len = inputStream.read(bytes)) != -1) {
            sb.append(new String(bytes, 0, len));
        }
        Map<String, String> map = WXPayUtil.xmlToMap(sb.toString());
        System.out.println(map);
        if (map.get("return_code").equals("SUCCESS") && !map.isEmpty()) {
            //支付成功
            //修改订单状态为待发货已支付
            String orderId = map.get("out_trade_no");
            int i = orderService.updateOrderStatus(orderId, "2");
            //通过websocket连接向前端发送消息
            if (i > 0) {
                webSocketServer.sendMessage(orderId,"1");
                //响应微信支付平台
                Map<String, String> resMap = new HashMap<>();
                resMap.put("return_code", "SUCCESS");
                resMap.put("return_msg", "OK");
                resMap.put("appid", map.get("appid"));
                String resXml = WXPayUtil.mapToXml(resMap);
                return resXml;
            }
        }
        return null;

    }
    @ApiOperation("模拟支付成功操作")
    @GetMapping("/test/{orderId}")
    public ResultVo test(@PathVariable("orderId") String orderId) throws Exception {
        webSocketServer.sendMessage(orderId,"1");
        int i = orderService.updateOrderStatus(orderId, "2");
        if (i > 0) {
            return ResultVo.success(null);
        }else {
            return ResultVo.fail(ResCode.ORDER_ERROR);
        }
    }


}
